package com.ciwong.epaper.modules.evaluate.ui;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.bean.WorkAnswers;
import com.ciwong.epaper.modules.evaluate.bean.AnswerRecorder;
import com.ciwong.epaper.modules.evaluate.bean.RepeatAnswerInfo;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.modules.me.ui.JsonParserUtil;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.widget.ColorationTextView;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.play.OnPlayListener;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.ViewHolder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by keepon on 2017/4/26.
 */
public class RereadWordResultAdapter extends BaseAdapter {
    private Context mContext;

    private List<WordDetail> mWordDetailList;
    private List<AnswerRecorder> mAnswerRecorderList;
    private ArrayList<WorkAnswers<RepeatAnswerInfo>> mWorkAnswers;
    private int mSelectItem = 0;

    private ReReadWordListener reReadWordListener;

    private ImageView lastplay;

    private boolean mIsKaoShiMode;

    private boolean serviceExpired;

    public RereadWordResultAdapter(Context context, List<WordDetail> wordDetailList, List<AnswerRecorder> answerRecorderList, ArrayList<WorkAnswers<RepeatAnswerInfo>> workAnswers, boolean mIsKaoShiMode, boolean serviceExpired) {
        mContext = context;
        mWordDetailList = wordDetailList;
        mAnswerRecorderList = answerRecorderList;
        mWorkAnswers = workAnswers;
        this.mIsKaoShiMode = mIsKaoShiMode;
        this.serviceExpired = serviceExpired;
    }

    public void setReReadWordListener(ReReadWordListener reReadWordListener) {
        this.reReadWordListener = reReadWordListener;
    }

    public interface ReReadWordListener {
        public void reReadWord(int position);
    }

    @Override
    public int getCount() {
        return mWordDetailList == null ? 0 : mWordDetailList.size();
    }

    @Override
    public Object getItem(int position) {
        if (mAnswerRecorderList != null || mWordDetailList != null) {
            String words = mWordDetailList.get(position).getWords();
            String pretations = mWordDetailList.get(position).getPretations();
            String symbol = mWordDetailList.get(position).getSymbol();
            if (symbol != null) {
                if (!symbol.startsWith("[")) {
                    symbol = "[" + symbol;
                }
                if (!symbol.endsWith("]")) {
                    symbol += "]";
                }
            }
            int score = mAnswerRecorderList.get(position).getScore();
            String soundUrl = mAnswerRecorderList.get(position).getSoundUrl();
            EvaluateResult evaluateResult = null;
            if (mWorkAnswers != null && mWorkAnswers.size() > 0 && mWorkAnswers.size() > position) {
                WorkAnswers<RepeatAnswerInfo> repeatAnswerInfoWorkAnswers = mWorkAnswers.get(position);
                if (repeatAnswerInfoWorkAnswers != null && repeatAnswerInfoWorkAnswers.getAnswers() != null && repeatAnswerInfoWorkAnswers.getAnswers().size() > 0) {
                    RepeatAnswerInfo repeatAnswerInfo = repeatAnswerInfoWorkAnswers.getAnswers().get(0);
                    if (repeatAnswerInfo != null && EApplication.isSymbolColoration) {
                        evaluateResult = JsonParserUtil.fromJson(repeatAnswerInfo.getLines(), EvaluateResult.class);
                    }
                }

            }

            return new RereadWordItemBean(words, pretations, score, soundUrl, evaluateResult, symbol);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View v;
        if (convertView == null) {
            v = View.inflate(mContext, R.layout.adapter_reread_word_result_item, null);
        } else {
            v = convertView;
        }
        ImageView title_bar_iv = ViewHolder.get(v, R.id.title_bar_iv);
        ImageView tx_sentence_retry = ViewHolder.get(v, R.id.tx_sentence_retry);
        TextView word = ViewHolder.get(v, R.id.words_tv);
        TextView wordPretation = ViewHolder.get(v, R.id.pretations_tv);
        TextView score = ViewHolder.get(v, R.id.score_tv);
        LinearLayout word_result_lay = ViewHolder.get(v, R.id.word_result_lay);
        ColorationTextView colorRationTv = ViewHolder.get(v, R.id.coloration_tv);
        final ImageView audioImg = ViewHolder.get(v, R.id.audio_img);
        final RereadWordItemBean itemBean = (RereadWordItemBean) getItem(position);
        word.setText(itemBean.getWords());
        wordPretation.setText(itemBean.getPretations());
        score.setText(String.valueOf(itemBean.getScore()));
        if (EApplication.isSymbolColoration) {
            if (itemBean.getEvaluateResult() != null) {
                colorRationTv.setVisibility(View.VISIBLE);
                if (serviceExpired) {
                    colorRationTv.setSymbolColoration(itemBean.getEvaluateResult(), itemBean.getSymbol());
                } else {
                    colorRationTv.setSymbolText(itemBean.getEvaluateResult(), itemBean.getSymbol());
                }
            } else {
                colorRationTv.setVisibility(View.GONE);
            }
        } else {
            colorRationTv.setVisibility(View.GONE);
        }
        if (serviceExpired) {
            int scoreColor;
            int wordColor;

            if (itemBean.getScore() < SpeechUtils.SCORE_6) {
                scoreColor = R.color.score_red;
                wordColor = R.color.me_item_name_sub_txt_color;
            } else if (itemBean.getScore() < SpeechUtils.SCORE_2) {
                scoreColor = R.color.score_red;
                wordColor = R.color.score_red;
            } else if (itemBean.getScore() < SpeechUtils.SCORE_4) {
                scoreColor = R.color.score_yellow;
                wordColor = R.color.score_yellow;
            } else {
                scoreColor = R.color.score_green_word;
                wordColor = R.color.score_green_word;
            }
            if (itemBean.getScore() == -1 || mIsKaoShiMode) {
                scoreColor = R.color.me_item_name_sub_txt_color;
                wordColor = R.color.me_item_name_sub_txt_color;
            }
            score.setTextColor(mContext.getResources().getColor(scoreColor));
            word.setTextColor(mContext.getResources().getColor(wordColor));
            title_bar_iv.setBackgroundColor(mContext.getResources().getColor(wordColor));
        } else {
            word.setTextColor(mContext.getResources().getColor(R.color.black));
            score.setText("已提交");
            score.setTextSize(14);
            score.setTextColor(mContext.getResources().getColor(R.color.color_light_green));
        }

        tx_sentence_retry.setVisibility(View.GONE);
        score.setVisibility(View.VISIBLE);
        //只有练习模式才能重读
        if (!mIsKaoShiMode) {
            score.setOnClickListener(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    //重读逻辑相关
                    reReadWordListener.reReadWord(position);
                }
            });

            word_result_lay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    reReadWordListener.reReadWord(position);
                }
            });
        }
//        }
        if (mIsKaoShiMode) {
            //非练习模式不显示分数和重读按钮及染色音标
            colorRationTv.setVisibility(View.GONE);
            tx_sentence_retry.setVisibility(View.GONE);
            score.setVisibility(View.GONE);
        }
        audioImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String soundUrl = itemBean.getSoundUrl();
                File file = new File(soundUrl);
                if (file == null || !file.exists()) {
                    soundUrl = FileUtil.getReNameFilePath(soundUrl);
                }
                if (lastplay != null) {
                    lastplay.setImageResource(R.mipmap.icon_sound_gray);
                }
                //soundUrl = "/storage/emulated/0/ciwong/newspaper/answers/nupload/www/uploadedfile_86562745-1808-40c6-9622-026c11d386596a6334b478289b4fb3060c4f803eafd3.mp3";

                lastplay = audioImg;
                audioImg.setImageResource(R.drawable.reread_bg_annimation);
                final AnimationDrawable animationDrawable = (AnimationDrawable) audioImg.getDrawable();
                animationDrawable.start();
                AudioPlayer.getInstance().setOnPlayListener(new OnPlayListener() {
                    @Override
                    public void onReadPlayer(long l, Object o) {

                    }

                    @Override
                    public void onPlayStart(Object o) {

                    }

                    @Override
                    public void stop(Object o) {
                        animationDrawable.stop();
                        audioImg.setImageResource(R.mipmap.icon_sound_gray);
                    }

                    @Override
                    public void onError(int i, Object o) {
                        animationDrawable.stop();
                        audioImg.setImageResource(R.mipmap.icon_sound_gray);
                    }

                    @Override
                    public void onBuffer(Object o, long l, long l1) {

                    }

                    @Override
                    public void onPlaying(long l, long l1) {

                    }
                }).play(BaseConstants.FILE_PREFIX + soundUrl, null);
                try {
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                        MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                        if (mMediaPlayer != null) {
                            try {
                                PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                                if (params != null) {
                                    mMediaPlayer.setPlaybackParams(params);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return v;
    }

    public void setSelectItem(int selectItem) {
        mSelectItem = selectItem;
    }

}
